import {requestPayment,showToast,showModal} from "../../utils/youHuaWxAPI";
import {request} from "../../request/request";
import regeneratorRuntime from "../../lib/runtime/runtime";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalNum: 0,
    totalPrice: 0
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取缓存中的用户获货地址
    const address = wx.getStorageSync("address") || {};
    // 获取缓存中用户的购物车信息
    let cart = wx.getStorageSync("cart") || [];
    // 过滤出用户要购买的商品
    cart = cart.filter(v => v.checked);
    let totalNum = 0;
    let totalPrice = 0;
    cart.forEach(v => {
      totalNum += v.num;
      totalPrice += v.num * v.goods_price;
    });
    this.setData({address,cart,totalNum,totalPrice});
  },

  // 处理用户点击支付
  async handleOrderPay() {
    try 
    {
      /* 本地缓存有token则前往付款操作，
        否则让用户授权获取用户信息，
        并拿用户信息发送请求获取token
      */
      const 
        token = wx.getStorageSync("token"),
        userInfo = wx.getStorageSync("userInfo");
      if (!userInfo)   // 实际开发时括号里放的是token
      {
        // console.log(Object.is('',token));
        const res = await showModal({content: "您尚未登录，前往登录？"});
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/user/index'
          });
        }
        return;          
      }
      // 实际开发没有下面这两行
      await showToast({title: "支付功能正在开发中..."});
      return;
      // console.log("有token");
      /**
       * 个人微信小程序帐号无法发起支付功能，所以下面无法实现
       * 1.创建订单         获取订单号
       * 2.获取支付参数
       * 3.调起微信支付
       * 4.支付成功         删除已购买商品在购物车里的信息  跳转至订单页面
       */
      const
        // 请求头参数 
        // header = {Authorization: token},
        // 请求体参数
        order_price = this.data.totalPrice,
        consignee_addr = this.data.address.detailAddress,
        cart = this.data.cart;

      let goods = [];
      cart.forEach(v => {
        let obj = {
          goods_id: v.goods_id,
          goods_number: v.num,
          goods_price: v.goods_price
        };
        goods.push(obj);
      });
      // 订单号
      const {order_number} = await request({
        url: "/my/orders/create",
        data: {order_price,consignee_addr,goods},
        method: "POST"
      });
      // 支付参数
      const {pay} = await request({
        url: "/my/orders/req_unifiedorder",
        data: {order_number},
        method: "POST"
      });

      // 调起微信支付
      const payResult = await requestPayment(pay);
      // console.log(payResult);

      // 后台查询 订单支付情况
      const backResult = await request({
        url: "/my/orders/chkOrder",
        data: {order_number},
        method: "POST"        
      });
      // console.log(backResult);
      await showToast({title: "支付成功！"});

      // 清除已购买商品的信息
      let newCart = wx.getStorageSync("cart");
      newCart = newCart.filter(v => !v.checked);
      wx.setStorageSync("cart", newCart);

      // 跳转至订单页面
      wx.navigateTo({
        url: '/pages/order/index?type=1'
      });

    } catch (err) {
      await showToast({title: "支付失败！"});
      console.log(err);
    }
  }
})